package lagou.gateway.lagougateway.filter;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import lagou.gateway.lagougateway.utils.CacheUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RefreshScope
public class IpLimitFilter implements GlobalFilter, Ordered {


    @Value("${iplimit.times}")
    private Integer limitTimes;


    @Value("${time.limit}")
    private Integer timeLimit;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String hostString = exchange.getRequest().getRemoteAddress().getHostString();
        ServerHttpResponse response = exchange.getResponse();
        CacheUtil cache = CacheUtil.getInstance();
        Integer times = (Integer) cache.get(hostString);
        if (null == times) {
            cache.set(hostString, 1, timeLimit);
        } else {
            if (times >= limitTimes) {
                response.setStatusCode(HttpStatus.BAD_REQUEST);
                String data = "请求过于频繁";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            } else {
                cache.set(hostString, times + 1);
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
